package cn.hanyx.vlog.authservice.controller;

import cn.hanyx.vlog.authservice.dto.ResponseObject;
import cn.hanyx.vlog.authservice.entity.User;
import cn.hanyx.vlog.authservice.service.AuthService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.crypto.SecretKey;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * AuthController
 *
 * @author CSS
 * @date 2021/11/10
 */
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    @Value("${app.secretKey}")
    private String secretKey = null;

    @PostMapping("/auth")
    public ResponseObject<Map> auth(String username, String password) {
        ResponseObject<Map> responseObject;
        try {
            User user = authService.auth(username, password);
            Map<String, Object> map = new LinkedHashMap();
            map.put("user", user);
            //1.对秘钥做BASE64编码
            String base64 = new BASE64Encoder().encode(secretKey.getBytes());
            //2.生成秘钥对象,会根据base64长度自动选择相应的 HMAC 算法
            SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes());
            //3.利用JJWT生成Token
            ObjectMapper objectMapper = new ObjectMapper();
            user.setPassword(null);
            String userJson = objectMapper.writeValueAsString(user);
            String jwt = Jwts.builder().setSubject(userJson).signWith(secretKey).compact();
            map.put("token", jwt);
            responseObject = new ResponseObject<>(map);
        } catch (Exception e) {
            e.printStackTrace();
            responseObject = new ResponseObject<>(e.getClass().getSimpleName(), e.getMessage());
        }
        return responseObject;
    }
}
